from django.shortcuts import render
from django.http import JsonResponse
from django.views import View
from api import serializer

class InfoView(View):
    """资讯相关接口"""

    def get(self, request,*args, **kwargs):
        data = [
                {'id': 1, 'title': 'xxx'},
                {'id': 2, 'title': 'xxxxx'}
            ]

        return JsonResponse(data,safe=False)

    def post(self, request, *args, **kwargs):
        pass

from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.response import Response
from api import models
from django.forms import model_to_dict
import json

class DrfInfoView(APIView):
    def get(self, request, *args, **kwargs):
        data = [
            {'id': 1, 'title': 'xxx'},
            {'id': 2, 'title': 'xxxxx'}
        ]
        return Response(data)


class DrfCategoryView(APIView):
    def get(self, request, *args, **kwargs):
        """获取所有文章分类/单个文章"""
        pk = kwargs.get('pk')
        if not pk:
            queryset = models.Category.objects.all().values('id', 'name')
            category_list = list(queryset)
            return Response(category_list)
        queryset = models.Category.objects.filter(id=pk).first()
        category_list = model_to_dict(queryset)
        return Response(category_list)

    def post(self, request, *args, **kwargs):
        """增加一条分类信息"""
        #原始数据
        # info_dict = json.loads(request.body.decode('utf-8'))
        # print(info_dict)
        print(request.data)
        # name = request.POST.get('name','')
        # Category.objects.create(name=name)
        models.Category.objects.create(**request.data) # 打散
        return Response("Success")

    def delete(self, request, *args, **kwargs):
        """删除"""
        pk = kwargs.get('pk')

        models.Category.objects.filter(pk=pk).delete()
        return Response("删除成功")

    def put(self, request, *args, **kwargs):
        """更新"""
        pk = kwargs.get('pk')
        models.Category.objects.filter(pk=pk).update(**request.data)
        return Response("更新成功")


# ####################################
from rest_framework import serializers

class NewCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Category
        fields = ['id', 'name']


class NewCategoryView(ListAPIView, RetrieveAPIView):
    queryset = models.Category.objects.all()
    serializer_class = NewCategorySerializer



"""
class NewCategoryView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if not pk:
            queryset = models.Category.objects.all()
            ser = NewCategorySerializer(instance=queryset, many=True)   # 有多条数据需要添加many=True
            return Response(ser.data)
        else:
            queryset = models.Category.objects.filter(pk=pk).first()
            ser = NewCategorySerializer(instance=queryset, many=False)
            return Response(ser.data)

    def post(self, request, *args, **kwargs):
        ser = NewCategorySerializer(data = request.data)
        if ser.is_valid():
            ser.save()
            return Response(data=ser.data)
        return Response(ser.errors)

    def put(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        category_obj = models.Category.objects.filter(pk=pk).first()
        ser = NewCategorySerializer(instance=category_obj, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response(ser.data)
        return Response(ser.errors)

    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        Category.objects.filter(pk=pk).delete()
        return Response("删除成功")
"""




class ArticleView(APIView):
    """文章操作"""
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if not pk:
            queryset = models.Article.objects.all().values('id', 'title', 'summary', 'content', 'category__name', 'category_id')
            article_list = list(queryset)
            return Response(article_list)
        else:
            queryset = models.Article.objects.filter(pk=pk).first()
            article_list = model_to_dict(queryset)
            return Response(article_list)

    def post(self, request, *args, **kwargs):
        models.Article.objects.create(**request.data)
        return Response("添加成功")

    def put(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        models.Article.objects.filter(pk=pk).update(**request.data)
        return Response("修改成功")

    def patch(self, request, *args, **kwargs):
        pass


    def delete(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        models.Article.objects.filter(pk=pk).delete()
        return Response("删除成功")



class NewArticleView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if not pk:
            queryset = models.Article.objects.all()
            ser = serializer.NewArticleSerializer(instance=queryset, many=True)
            return Response(ser.data)
        else:
            queryset = models.Article.objects.filter(pk=pk).first()
            ser = serializer.NewArticleSerializer(instance=queryset, many=False)
            return Response(ser.data)

    def post(self, request, *args, **kwargs):
        print(request.data)
        ser = serializer.FormNewArticleSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            print(ser.validated_data)
            return Response("添加成功")
        print(ser.errors)
        return Response(ser.errors)

    def put(self, request, *args, **kwargs):
        """全部更新"""
        pk = kwargs.get('pk')
        article_obj = models.Article.objects.filter(pk=pk).first()
        ser = serializer.FormNewArticleSerializer(instance=article_obj, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response("修改成功")
        print(ser.errors)
        return Response("修改失败")

    def patch(self, request, *args, **kwargs):
        """局部更新"""
        pk = kwargs.get('pk')
        article_obj = models.Article.objects.filter(pk=pk).first()
        ser = serializer.FormNewArticleSerializer(instance=article_obj, data= request.data)
        if ser.is_valid():
            ser.save()
            return Response("更新成功")
        print(ser.errors)
        return Response("更新失败")




class TagView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if not pk:
            queryset = Tag.objects.all()
            ser = serializer.TagSerializer(instance=queryset, many=True)
            return Response(ser.data)
        else:
            tag_obj = Tag.objects.filter(pk=pk).first()
            ser = serializer.TagSerializer(instance=tag_obj, many=False)
            return Response(ser.data)

    def post(self, request, *args, **kwargs):
        ser = serializer.TagSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response("添加标签成功")
        else:
            print(ser.errors)
            return Response(ser.errors)


from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination
from rest_framework import serializers


class HulaPageNumberPaginat(LimitOffsetPagination):
    max_limit = 20

class PageArticleSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        fields = '__all__'

class MyPageNumberPagination(PageNumberPagination):
    page_size = 2

class PageArticleView(APIView):
    def get(self, request, *args, **kwargs):
        queryset = models.Article.objects.all()

        # 方式一
        """
        
        # 分页对象
        page_object = MyPageNumberPagination()
        # 调用 分页对象.paginate_queryset方法进行分页，得到的结果是分页之后的数据
        result = page_object.paginate_queryset(queryset, request, self)
        # result就是分完页的一部分数据
        print(result)

        ser = PageArticleSerializers(instance=result, many=True)
        return Response(ser.data)
        """
        '''
        # 方式二： 数据 + 分页信息
        page_object = MyPageNumberPagination()
        result = page_object.paginate_queryset(queryset, request, self)
        print(result)

        ser = PageArticleSerializers(instance=result, many=True)
        return page_object.get_paginated_response(ser.data)
        '''

        '''
        # 方式三： 数据 + 部分分页信息
        page_object = MyPageNumberPagination()
        result = page_object.paginate_queryset(queryset, request, self)
        print(result)
        ser = PageArticleSerializers(instance=result, many=True)
        return Response({"count":page_object.page.paginator.count, "result": ser.data})
        '''


        # 方式三： 数据 + 部分分页信息
        page_object = HulaPageNumberPaginat()
        result = page_object.paginate_queryset(queryset, request, self)
        print(result)
        ser = PageArticleSerializers(instance=result, many=True)
        return Response({"count":page_object.count, "result": ser.data})


from rest_framework.generics import ListAPIView

class PageViewArticleSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        fields = '__all__'

class PageViewArticleView(ListAPIView):
    queryset = models.Article.objects.all()
    serializer_class = PageViewArticleSerializers
